'''
实现将english语言key为关键字，找到对应的翻译文本并写入excel表格中。
如果对应的key在对应翻译中没有，则表格中的值为空，需要人为补上
'''
#通过命令行将脚本转为.xls
import os,time,sys
import xlwt,re
import execjs
from conf.setting import special_mark
BASE_DIR=os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0,BASE_DIR)
from php import PHP  #执行php代码的类
from resolve_file import special_write_xls  #处理特殊文件validate_en.js文件

gen_addr = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def run(Language_list):
    while True:
        print(Language_list)
        choose_lang = input('Select a language from the list above>>:').strip().lower()
        if choose_lang in Language_list:
            print('wait a moment...')
            break
        else:
            print(' Wrong input,please input again.')
            continue

    #输入正确后执行
    
    Lang_addr = os.path.join(gen_addr,'lang',choose_lang)
    #en语言列表目录
    global en_Lang_addr
    en_Lang_addr = os.path.join(gen_addr,'lang','en')  
    #调取函数
    readDir(en_Lang_addr,choose_lang)

#先读一个文件
def readFileData(file0):
    #判断file0文件是否
    if not os.path.exists(file0):
        return False
    file_ext = file0.split('.')[1]  #获取文件后缀名 js  php
    with open(file0,'r', encoding='utf-8') as fo:
        ret_data = fo.read()
        #print(ret_data)
        if file_ext == 'js':
            #函数名称
            func_name = ''
            ret_data = re.findall('({[^\{\}]*})',ret_data)
            ret_data = ret_data[0]
            ret_data = execjs.get(execjs.runtime_names.Node).eval(ret_data)
            
        elif file_ext == 'php':
            lines = fo.seek(0,0)  #指针重置到文件开头
            lines = fo.readlines()  #读取所有行
            len_lines = len(lines)  #文件的行数
            if  not '?>' in lines[len_lines-1]:   #判断php文件末尾是否加了?>
                ret_data = ret_data + '?>'
            
            #函数名称
            tmp_php = os.path.join(gen_addr,'ci18n','core','tmp_php.php')
            func_name = re.findall('function ([\w]*)',ret_data)[0]
            with open(tmp_php, 'w', encoding='utf-8') as fi:
                fi.write(ret_data)
                fi.write(os.linesep+'<?php'+os.linesep)
                fi.write('echo json_encode('+func_name+'())'+os.linesep)
                fi.write('?>')
            php1 =PHP(tmp_php) 
            ret_data = php1.get()
    # 返回得到的json数据和 php函数名
    return (ret_data, func_name)

#读取目录所有文件列表
'''
参数1 表示文件目录地址
参数2 表示选择的转换语言
'''
def readDir(fileDir,choose_lang):
    fileList = os.listdir(fileDir)  #所有文件列表
    book = xlwt.Workbook(encoding='utf-8')  
    sheet1 = book.add_sheet('sheet1')
    style = xlwt.easyxf('alignment: horz center, vert center')      #设置样式，居中 
    sheet1.write_merge(0,0,0,6,choose_lang,style)
    sheet1.col(0).width =0  #30个字符宽度，一个字节为256，关键key隐藏
    sheet1.col(1).width =30000  #英语值
    sheet1.col(2).width =30000  #所要填的语言值
    sheet1.col(3).width =0  #文件名
    #php函数名 或者validate_en.js下的某key值是否有jQuery.validator.format标记
    sheet1.col(4).width =0  
    sheet1.col(5).width =0  #是否为list
    sheet1.col(6).width =0  #特殊标记的个数
    write_row = 0 #写的行数

    #写数据百分比完成度
    print('0%'.center(50,'-'))
    for index,ori_filename in enumerate(fileList):
        file_ext = ori_filename.split('.')[1]  #获取文件后缀名 js  php
        filename = ori_filename.replace('_en.'+file_ext,'')  #文件名
        file0 = os.path.join(gen_addr,'lang','en', ori_filename)
        filename = filename + '_' +choose_lang + '.' +file_ext #base_tr.js
        file1 = os.path.join(gen_addr,'lang', choose_lang, filename)
        if ori_filename == 'validate_en.js':
            #print(ori_filename)
            # 直接放到另外一个文件的函数里处理
            write_row = special_write_xls(write_row,file0,file1,sheet1,filename)
             #写数据百分比完成度
            print(('%d%%' % int((index+1)*100/len(fileList)) ).center(50,'-'))
            continue
        
        ret_data1 = readFileData(file0)  #读en源文件中的数据
        ret_data2 = readFileData(file1)  #读所选择的语言的数据
        
        for key1 in ret_data1[0]: #数据部分
            write_row +=1
            
            sheet1.write(write_row,0,str(key1))   #key
            
            if type(ret_data1[0][key1]) ==list: #如果是数组，则将值用,连接
                value1 = ','.join(ret_data1[0][key1])
                sheet1.write(write_row,1,value1) #key对应语言值
                sheet1.write(write_row,5,'list') #key对应语言值
            else:
                sheet1.write(write_row,1,str(ret_data1[0][key1]))  #key对应的英语值

            #查找特殊标记的个数
            num = 0
            for mark in special_mark:
                data_tmp = ''
                if type(ret_data1[0][key1]) ==list:
                    data_tmp = ','.join(ret_data1[0][key1])
                else:
                    data_tmp = ret_data1[0][key1]
                num += len(re.findall(mark,str(data_tmp)))

            sheet1.write(write_row,6,num)

            if not ret_data2== False:
                if key1 in ret_data2[0]:
                    if type(ret_data1[0][key1]) ==list: #如果是数组，则将值用,连接
                        value2 = ','.join(ret_data2[0][key1])
                        sheet1.write(write_row,2,value2) #key对应语言值
                    else:
                        sheet1.write(write_row,2,str(ret_data2[0][key1])) #key对应语言值
                else:
                    pass
                    #sheet1.write(write_row,2,'')
            else:
                pass
                #sheet1.write(write_row,1,'')
            sheet1.write(write_row,3,filename)  #写文件名
            sheet1.write(write_row,4,ret_data1[1])  #写php函数名
            
        print(('%d%%' % int((index+1)*100/len(fileList)) ).center(50,'-'))

    #excel文件保存地址
    excel_addr = os.path.join(gen_addr,'ci18n','excel_product',choose_lang)
    book.save(excel_addr+'.xls')
    #将php临时文件删除
    tmp_php = os.path.join(gen_addr,'ci18n','core','tmp_php.php')
    if os.path.exists(tmp_php):
        os.remove(tmp_php)
    print('work done.')